import REQ, {ResData} from "@/utils/ApiUtil.ts";
import LocalUtil from "@/utils/LocalUtil.ts";
import defaultAvatar from "@/static/defaultAvatar.ts";
import tokenUtil from "@/utils/TokenUtil.ts";
import {ICreateUserInfoVo, IPage, IUserInfoDto, IUserLoginVo} from "@/api/Types/ObjInterfaces.ts";

class UserApi {

    /**
     * 创建新用户
     * @param _data 新用户数据
     */
    public createUser = async (_data: ICreateUserInfoVo): Promise<void> => {
        const data: ICreateUserInfoVo = {
            username: _data.username,
            password: _data.password,
            nickName: _data.nickName,
        }

        await REQ.post<IUserLoginVo, ResData<string>>("api/user/create", data)
    }

    /**
     * 用户登录
     * @param _data 用户登录参数
     */
    public login = async (_data: IUserLoginVo): Promise<IUserInfoDto | null> => {
        const data: IUserLoginVo = {
            username: _data.username,
            password: _data.password,
        }

        const data_1 = await REQ.post<IUserLoginVo, ResData<string>>("api/user/login", data);
        if (data_1 == null) {
            return null;
        }
        const token = data_1.data;
        LocalUtil.saveToken(token);
        const userInfo = tokenUtil.parseToken(token);
        window.messageApi.success("登录成功").then();
        return userInfo;
    }

    /**
     * 获取当前用户的头像链接，写入img标签，由浏览器自行请求
     */
    public getAvatarLink = (): string => {
        const userInfo = LocalUtil.getUserInfoDto();
        if (userInfo == null || userInfo.avatar == null) {
            return defaultAvatar
        } else {
            return 'api/img/' + userInfo.avatar
        }
    }

    public getUserById = async (id: string) => {
        const res = await REQ.get('api/user/' + id)
        return res.data
    }

    /**
     * 分页获取用户信息
     */
    public pageUser = async (currentPage?: number, pageSize?: number): Promise<IPage<IUserInfoDto>> => {
        const data = await REQ<any, ResData<IPage<IUserInfoDto>>>({
            method: 'get',
            url: "api/user/page",
            params: {
                current: currentPage,
                size: pageSize
            },
        })
        return data.data
    }

    /**
     * 退出登录
     */
    public logout = () => {
        LocalUtil.removeToken()
    }
}

export default new UserApi()